﻿#include "facecollect.h"
#include "ui_facecollect.h"
#include <QSqlRecord>
#include <QDebug>
faceCollect::faceCollect(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::faceCollect)
{
    ui->setupUi(this);
    this->setWindowFlag(Qt::FramelessWindowHint);
    facelabel[0] = ui->face1;
    facelabel[1] = ui->face2;
    facelabel[2] = ui->face3;
    count = 0;

    //导入haarcascade_frontalface_alt2.xml--人脸特征文件
    cascade.load("./haarcascade_frontalface_alt2.xml");
    this->startTimer(100);
    cap.open(0);//打开摄像头 0 笔记本摄像头 1 外部USB摄像头

}

faceCollect::~faceCollect()
{
    delete ui;
}

void faceCollect::timerEvent(QTimerEvent *e)
{
    Mat imageMat;

    cap>>imageMat; //cap.read(imageMat);
    //放缩
    Mat srcMat;
    cv::resize(imageMat, srcMat, Size(ui->facelabel->width(), ui->facelabel->height())); //设置摄像头采集的画面和标签的大小一样

    Mat grayMat;
    cvtColor(srcMat, grayMat, CV_BGR2GRAY);//转灰度图--二值化
    //检测人脸
    std::vector<Rect> faceRects;
    cascade.detectMultiScale(grayMat, faceRects, 1.1,3,0, Size(100,100));

    if(faceRects.size()>0)
    {
        //绘制矩形框
        rectangle(srcMat,faceRects[0],Scalar(255,0,0));
        face = grayMat(faceRects[0]);
    }

    //把Mat数据转QImage
    QImage image(srcMat.data, srcMat.cols, srcMat.rows, srcMat.step1(), QImage::Format_RGB888);
    ui->facelabel->setPixmap(QPixmap::fromImage(image));
}

void faceCollect::on_collectbt_clicked()
{
    if(face.data == nullptr) return;

        int label = ui->numberEdit->text().toInt();
        QString name=ui->nameEdit->text();


        tranLabels.push_back(label);

        cv::resize(face, face, Size(100,100));

        tranImages.push_back(face);
        //把Mat数据转QImage
        QImage image(face.data, face.cols, face.rows, face.step1(), QImage::Format_Grayscale8);
        facelabel[count++]->setPixmap(QPixmap::fromImage(image));
        if(count == 3) count = 0;


}

void faceCollect::on_trainbt_clicked()
{

    QString name=ui->nameEdit->text();
    int faceID=ui->numberEdit->text().toInt();
    QString path=QString("A:/projectQT/faceProject/image/face%1.jpg").arg(faceID);

    QString insertSql = QString("insert into faceInfo(name,faceID,picturepath,signltime,flage)"
                                "values('%1','%2','%3','%4','%5')")
                                .arg(name).arg(faceID).arg(path).arg("0").arg(0);
    QSqlQuery query;
    if(!query.exec(insertSql))
      {
          qDebug()<<query.lastError().text();
      }

    Ptr<FaceRecognizer> model =EigenFaceRecognizer::create();
    //导入原来的数据
    //cv::String file = "./face.xml";
    //model->read(file);
    //训练
    model->train(tranImages, tranLabels);
    model->save("face.xml");
}

void faceCollect::on_pushButton_clicked()
{
    faceProject *win = new faceProject;
    win->show();
    this->close();
}
